/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.Track;
import com.jeeplus.modules.tms.service.TrackService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.NewBill;
import com.jeeplus.modules.tms.service.NewBillService;

/**
 * 运单Controller
 * @author 李超辉
 * @version 2019-04-29
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/newBill")
public class NewBillController extends BaseController {

	@Autowired
	private NewBillService newBillService;
	@Autowired
	private TrackService trackService;
	
	@ModelAttribute
	public NewBill get(@RequestParam(required=false) String id) {
		NewBill entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = newBillService.get(id);
		}
		if (entity == null){
			entity = new NewBill();
		}
		return entity;
	}
	/**
	 * 在途跟踪
	 */
	@ResponseBody
	@RequestMapping(value = "ztgz")
	public AjaxJson ztgz(String ids,String dd,String lk,String yjdd,String bz, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00");
		for(String i:ids.split(",")){
			NewBill n=newBillService.get(i);
			n.setZxsj(sdf.parse(dd));
			n.setZxwz(lk);
			n.setYjdd(sdf.parse(yjdd));
			newBillService.save(n);
			Track t=new Track();
			t.setLx("电话跟踪");
			t.setBill(i);
			t.setRemarks(bz);
			t.setSj(sdf.parse(dd));
			t.setWz(lk);
			trackService.save(t);
		}
		j.setMsg("跟踪成功");
		return j;
	}

	/**
	 * 签收
	 */
	@ResponseBody
	@RequestMapping(value = "qs")
	public AjaxJson qs(NewBill n,String qsr,String qssj,String qsjs,String qszt,String bz, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00");
			n.setQssj(sdf.parse(qssj));
			n.setQsjs(qsjs);
			n.setStatus("已签收");
			n.setQsr(qsr);
		    n.setQszt(qszt);
		    n.setRemarks(bz);
			newBillService.save(n);

		j.setMsg("签收成功");
		return j;
	}




	/**
	 * 到货确认
	 */
	@ResponseBody
	@RequestMapping(value = "dhqr")
	public AjaxJson dhqr(String ids,String dd,String lk, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00");
		for(String i:ids.split(",")){
			NewBill n=newBillService.get(i);
			n.setDshd(sdf.parse(dd));
			n.setLkshd(sdf.parse(lk));
			n.setStatus("已到货");
			newBillService.save(n);
		}
		j.setMsg("到货确认成功");
		return j;
	}

	/**
	 * 到公司
	 */
	@ResponseBody
	@RequestMapping(value = "dgs")
	public AjaxJson dgs(String ids, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		for(String i:ids.split(",")){
			NewBill n=newBillService.get(i);
			n.setDgssj(new Date());
			n.setStatus("回单到公司");
			newBillService.save(n);
		}
		j.setMsg("确认成功");
		return j;
	}

	/**
	 * 到货确认
	 */
	@ResponseBody
	@RequestMapping(value = "dhz")
	public AjaxJson dhz(String ids, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		for(String i:ids.split(",")){
			NewBill n=newBillService.get(i);
			n.setDhzsj(new Date());
			n.setStatus("回单到货主");
			newBillService.save(n);
		}
		j.setMsg("确认成功");
		return j;
	}


	/**
	 * 运单列表页面
	 */
	@RequiresPermissions("tms:newBill:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/newBillList";
	}
	
		/**
	 * 运单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:newBill:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(NewBill newBill, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newBill.setPro(pro);}
		Page<NewBill> page = newBillService.findPage(new Page<NewBill>(request, response), newBill);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑运单表单页面
	 */
	@RequiresPermissions(value={"tms:newBill:view","tms:newBill:add","tms:newBill:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(NewBill newBill, Model model) {
		model.addAttribute("newBill", newBill);
		Track t=new Track();
		t.setBill(newBill.getId());
		List<Track> ts=trackService.findList(t);
		model.addAttribute("list", ts);
		return "modules/tms/newBillForm";
	}

	/**
	 * 保存运单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:newBill:add","tms:newBill:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(NewBill newBill, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, newBill)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		newBillService.save(newBill);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存运单成功");
		return j;
	}
	
	/**
	 * 删除运单
	 */
	@ResponseBody
	@RequiresPermissions("tms:newBill:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(NewBill newBill, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		newBillService.delete(newBill);
		j.setMsg("删除运单成功");
		return j;
	}
	
	/**
	 * 批量删除运单
	 */
	@ResponseBody
	@RequiresPermissions("tms:newBill:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			newBillService.delete(newBillService.get(id));
		}
		j.setMsg("删除运单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:newBill:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(NewBill newBill, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "运单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<NewBill> page = newBillService.findPage(new Page<NewBill>(request, response, -1), newBill);
    		new ExportExcel("运单", NewBill.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出运单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:newBill:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<NewBill> list = ei.getDataList(NewBill.class);
			for (NewBill newBill : list){
				try{
					newBillService.save(newBill);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条运单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条运单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入运单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/newBill/?repage";
    }
	
	/**
	 * 下载导入运单数据模板
	 */
	@RequiresPermissions("tms:newBill:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "运单数据导入模板.xlsx";
    		List<NewBill> list = Lists.newArrayList(); 
    		new ExportExcel("运单数据", NewBill.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/newBill/?repage";
    }

}